<?php

namespace app\service\payment\gateway;

use app\constant\CommonConstant;
use app\exception\BusinessException;
use app\helpers\FormatHelper;
use app\helpers\UtilHelper;
use app\libs\DianDianPaySDK\action\PaymentApi;
use app\libs\DianDianPaySDK\builder\DianDianPaymentBuilder;
use app\libs\PaypalSDK\action\PurchasePaypal;
use app\libs\PaypalSDK\builder\PurchaseBuilder;
use app\libs\PaypalSDK\builder\RepurchasePaypal;
use app\libs\SpreedlySDK\Action\PurchaseAPI;
use app\libs\SpreedlySDK\Builder\SpreedlyPurchaseBuilder;
use app\libs\WeChatSDK\Action\PushMessage;
use app\model\Notify;
use app\model\Orders;
use app\model\ShopsPayment;
use app\trait\ShopifyTrait;
use think\helper\Arr;
use think\Request;

class SpreedlyService implements PaymentInterface
{
    /**
     * @param Orders $order
     * @param Request $request
     * @return array
     * @throws \Exception
     * @desc 创建订单
     */
    public function placeOrder(Orders $order, Request $request): array
    {
        $payment_token = [];
        if ($card = $request->param("card", [])) {
            $holder = Arr::get($card, "holderName");
            $names = explode(' ', $holder);
            $payment_token = [
                    "credit_card" => [
                        "first_name" => Arr::first($names),
                        "last_name" => Arr::last($names),
                        'number' => Arr::get($card, "cardNumber"),
                        "month" => Arr::get($card, "expiryMonth"),
                        "year" => Arr::get($card, "expiryYear"),
                        "verification_value" => Arr::get($card, "cvv")
                    ]
                ];
            $order->card_number = Arr::get($card, "cardNumber");
        } elseif ($googlePay = $request->param("google_pay", [])) {
            $payment_token = [
                "google_pay" => $googlePay
            ];
        } elseif ($payment_method_token = $request->param("payment_method_token", [])) {
            $payment_token = ['payment_method_token' => $payment_method_token];
        }
        $order->payment_token = $payment_token;
        $order->save();
        $pay_result = $this->callSpreedlyAPI($order, $request);
        $approval_url = FormatHelper::getLoadingUrl(
            $order->shop->website,
            $order->checkout_id,
            [
                'cid' => $request->header("x-opc-client-id"),
                'order_id' => $order->id
            ]);
        $order_id= $order->id;
        return compact('approval_url','pay_result','order_id');
    }


    public function confirmPayment()
    {
        // TODO: Implement confirmPayment() method.
    }

    /**
     * @param Orders $order
     * @param Request $request
     * @return array
     * @throws \Exception
     * @desc 加购
     */
    public function repurchase(Orders $order, Request $request): array
    {
        $pay_result = $this->callSpreedlyAPI($order, $request);
        $target_url = FormatHelper::getLoadingUrl(
            $order->shop->website,
            $order->checkout_id,
            [
                'cid' => $request->header("x-opc-client-id"),
                'order_id' => $order->pid
            ]);
        return compact('target_url','pay_result');
    }


    //下单
    private function callSpreedlyAPI(Orders $order, Request $request)
    {
        $sdk = $order->payment->config;
        $gatewayToken = Arr::get($sdk, 'merchant_no');
        $builder = new SpreedlyPurchaseBuilder($order, $request);
        $body = $builder->toArray();
        $client = new PurchaseAPI($order->payment);
        $type = $order->is_repurchase ? Notify::TYPE_REPURCHASE : Notify::TYPE_PLACE_ORDER;
        try {
            $response = $client->purchase($gatewayToken, $body);
            Notify::saveParams($order->id, ['params' => $body, 'response' => $response,], $type, $order->pay_method);
            //保存结果
            $this->savePayResult($order, $response);
            return $response;
        } catch (\Exception $e) {
            Notify::saveParams($order->id, ['params' => $body, 'error' => $e->getMessage(),], $type, $order->pay_method);
            throw new \Exception($e->getMessage());
        }

    }

    //保存结果
    private function savePayResult(Orders $order, array $response = [])
    {
        if (empty($response)) return false;
        $isSave = false;
        $data = Arr::get($response, 'transaction', []);
        if ($tradeNo = Arr::get($data, 'token', '')) {
            $order->trade_no = $tradeNo;
            $isSave = true;
        }
        if ($orderNo = Arr::get($data, "order_id", '')) {
            $order->order_no = $orderNo;
            $isSave = true;
        }
        $pay_status = Arr::get($data, 'state', '');
        if ($pay_status) {
            $order->pay_status = $pay_status;
            $isSave = true;
        }
        if ($isSave) $order->save();
        $isSuccessed = Arr::get($data, 'succeeded', false);
        $message = Arr::get($data, 'message', '');
        if (!$isSuccessed) throw new BusinessException($message);
        Orders::completed($order);
        return true;
    }


}